import { App } from "vue"
/**
    created -- 在绑定元素的 attribute 或事件监听器被应用之前调用
    beforeMount -- 在绑定元素的父组件挂载之前调用
    mounted -- 绑定元素的父组件被挂载时调用
    beforeUpdate -- 在包含组件的 VNode 更新之前调用
    updated -- 在包含组件的 VNode 及其子组件的 VNode 更新之后调用
    beforeUnmount -- 在绑定元素的父组件卸载之前调用
    unmounted -- 卸载绑定元素的父组件时调用
 */
export default (app: App<Element>) => {
    //自定义组件
    app.directive('bubbling', {
        mounted(el: HTMLElement) {
            const parentEl = el.parentElement;
            if (parentEl) {
                parentEl.style.position = 'relative'
            }
            const radomArrItem = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)];
            const bubbleSizes = [3, 6, 9, 12];
            const bubbleColors = ["#DC143C", "#0066CC", "#333399", "#FFFF66"];
            let bubbleText: HTMLElement | null = el;
            if (bubbleText !== null) {
                const bubingFun = function () {
                    const bubbleSize: number = radomArrItem(bubbleSizes);
                    const textWidth: number = (bubbleText && bubbleText.offsetWidth) || 0;
                    const textSplitArrary: number[] = Array.from(Array(textWidth).keys());
                    let bubble = document.createElement("div");
                    bubble.className = "bubble";
                    bubble.style.width = `${bubbleSize}px`;
                    bubble.style.height = `${bubbleSize}px`;
                    bubble.style.left = `${radomArrItem(textSplitArrary)}px`;
                    bubble.style.background = `${radomArrItem(bubbleColors)}`;
                    bubble.style.position = `absolute`;
                    bubble.style.borderRadius = "100%";
                    bubble.style.zIndex = "-1";
                    bubbleText && bubbleText.append(bubble);
                    let bubbleAnimation = bubble.animate(
                        [
                            { bottom: "10%", opacity: 1, transform: "scale(1.5)" },
                            { bottom: "500%", opacity: 0, transform: "scale(0.8)" },
                        ],
                        {
                            fill: "forwards",
                            duration: 2000,
                        }
                    );
                    bubbleAnimation.onfinish = () => bubble.remove();
                    requestAnimationFrame(bubingFun);
                };
                requestAnimationFrame(bubingFun);
            }
        }
    });
}
